package pl.droidsonroids.gif;

import static pl.droidsonroids.gif.InvalidationHandler.MSG_TYPE_INVALIDATION;

import ohos.miscservices.timeutility.Time;

import java.util.concurrent.TimeUnit;

/**
 * RenderTask
 */
class RenderTask extends SafeRunnable {
    RenderTask(GifDrawable gifDrawable) {
        super(gifDrawable);
    }

    @Override
    public void doWork() {
        final long invalidationDelay = mGifDrawable.mNativeInfoHandle.renderFrame(mGifDrawable.mPixelMap);
        if (invalidationDelay >= 0) {
            mGifDrawable.mNextFrameRenderTime = Time.getRealActiveTime() + invalidationDelay;
            if (mGifDrawable.getVisible() && mGifDrawable.mIsRunning && !mGifDrawable.mIsRenderingTriggeredOnDraw) {
                mGifDrawable.mExecutor.remove(this);
                mGifDrawable.mRenderTaskSchedule = mGifDrawable.mExecutor.schedule(this, invalidationDelay,
                    TimeUnit.MILLISECONDS);
            }
            if (!mGifDrawable.mListeners.isEmpty() && mGifDrawable.getCurrentFrameIndex()
                == mGifDrawable.mNativeInfoHandle.getNumberOfFrames() - 1) {
                mGifDrawable.mInvalidationHandler.sendEvent(mGifDrawable.getCurrentLoop(),
                    mGifDrawable.mNextFrameRenderTime);
            }
        } else {
            mGifDrawable.mNextFrameRenderTime = Long.MIN_VALUE;
            mGifDrawable.mIsRunning = false;
        }
        if (mGifDrawable.getVisible() && !mGifDrawable.mInvalidationHandler.hasInnerEvent(MSG_TYPE_INVALIDATION)) {
            mGifDrawable.mInvalidationHandler.sendEvent(MSG_TYPE_INVALIDATION, 0);
        }
    }
}
